package org.ling.xuan.action;

import cn.hutool.core.util.StrUtil;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NotNull;
import org.ling.xuan.dao.FileDao;
import org.ling.xuan.entity.mo.CommonSetting;
import org.ling.xuan.extention.LxSql;
import org.ling.xuan.pannel.SqlUtilPanel;
import org.ling.xuan.util.LxOptional;

public class LxExecuteSqlAction extends AnAction {

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
        Project project = e.getProject();
        Editor editor = e.getDataContext().getData(com.intellij.openapi.actionSystem.PlatformDataKeys.EDITOR);
        String selectText = LxOptional.of(editor,ed->ed.getSelectionModel().getSelectedText()).orElse("");
        if (!StrUtil.isBlank(selectText)&&project!=null) {
            SqlUtilPanel sqlUtilPanel =LxSql.getPanel(project);
            if(sqlUtilPanel!=null){
                sqlUtilPanel.executeBatch(selectText);
            }
        }
    }


    @Override
    public void update(AnActionEvent e) {
        Editor editor = e.getDataContext().getData(com.intellij.openapi.actionSystem.PlatformDataKeys.EDITOR);
        String selectText = LxOptional.of(editor,ed->ed.getSelectionModel().getSelectedText()).orElse("");
        boolean f1 =StrUtil.isNotBlank(selectText);
        CommonSetting cs = FileDao.getCommonSetting();
        boolean f2 =StrUtil.isNotBlank(cs.getDbUrl());
        e.getPresentation().setEnabledAndVisible(f1&&f2);
    }
}
